<script setup lang="ts">
defineOptions({
  name: "Containers"
});
import {
  Refresh,
  SwitchButton,
  CircleCheck,
  Delete,
  CircleCheckFilled,
  Clock
} from "@element-plus/icons-vue";
import { useRoute, useRouter } from "vue-router";
import { onMounted, reactive, ref } from "vue";
import {
  getOneContainer,
  pauseContainer,
  unpauseContainer,
  getVolumeList,
  openContainer,
  startContainer,
  getContainerLog,
  getNetworkList,
  addNetwork,
  stopContainer,
  restartContainer,
  deleteContainer,
  clearContainerTraffic,
  selectServer,
  selectServerPlan,
  connectConsole,
  getContainerStatus,
  reinstallC,
  AdminDelHttps
} from "@/api/server";
import { getMirrorList } from "@/api/mirror";
import { message } from "@/utils/message";
import FileManage from "@/views/self/components/FileManage.vue";
import { delContainer, Containerpay, Containertime } from "@/api/user";
import { ElLoading } from "element-plus";
import AddHttps from "./components/AddHttps.vue";
const router = useRouter();
const route = useRoute();
//获取容器日志
const getLogs = async data => {
  let res3 = await getContainerLog(data);
  let newRes = res3.data.data;
  logTotal.value = res3.data.count;
  newRes = newRes.map(item => {
    return {
      created_at: item.created_at,
      action_info: item.action_info
    };
  });
  containers_log.value = newRes;
};
onMounted(async () => {
  setWideth();
  await getcontaiinfo();
  //获取容器卷列表
  let res2 = await getVolumeList(route.query.container_id);
  volumes.value = res2.data.data;
  //获取容器日志
  getLogs({ container_id: route.query.container_id, ...logPagin });
  // 获取容器网络列表
  await gettwolist();
});
// 获取容器信息
const getcontaiinfo = async (pay, time) => {
  let res = await getOneContainer({ container_id: route.query.container_id });
  if (res.data.data && !pay && !time) {
    console.log(res.data.data, "容器信息");
    contaimoney.value = res.data.data.pay;
    container_message.value = res.data.data;
    images.value = objectToString(res.data.data.env);
    await getImage();
    if (container_message.value.container_state > 1) {
      getStatus().catch(err => {
        container_message.value.container_state = 3;
      });
    } else {
      container_state.value = container_message.value.container_state;
    }
    conttimes.value = res.data.data.become_time;
  } else if (pay && !time) {
    contaimoney.value = res.data.data.pay;
  } else if (!pay && time) {
  }
};
// 获取容器网络列表
const gettwolist = async () => {
  let res4 = await getNetworkList(route.query.container_id);
  container_connect.value = res4.data;
  await getServerName();
  await getPlanName();
  // await getStatus();
};

//实时容器状态
const container_state = ref();
const getStatus = async () => {
  let res = await getContainerStatus({
    container_id: route.query.container_id
  });
  if (res.data.data.code == 200) {
    if (res.data.data.data.state === true) {
      container_state.value = 2;
    } else {
      container_state.value = 3;
    }
  } else {
    container_state.value = 3;
  }
};
//开通服务器
const openIt = async data => {
  let res = await openContainer({ container_id: data });
  console.log("开通容器", res);
  message(res.data.data, { type: "success" });
  await getStatus();
};
//开启容器
const startIt = async data => {
  let res = await startContainer({ container_id: data });
  console.log("开启容器", res);
  message(res.data.data, { type: "success" });
  await getStatus();
};
//关闭容器
const stopIt = async data => {
  let res = await stopContainer({ container_id: data });
  console.log("关闭容器", res);
  message(res.data.data);
  await getStatus();
};
//重启容器
const restartIt = async data => {
  let res = await restartContainer({ container_id: data });
  console.log("重启容器", res);
  message(res.data.data, { type: "success" });
  await getStatus();
};
//删除容器
const deleteIt = async data => {
  let res = await deleteContainer({ container_id: data });
  console.log("删除容器", res);
  message(res.data.data);
  await getStatus();
  router.push("/servers/containerlist");
};
const clearIt = async data => {
  let res = await clearContainerTraffic({ container_id: data });
  console.log("清空流量", res);
  message(res.data.data);
  await getStatus();
};
//连接控制台
const console_url = ref("");
const connectIt = async data => {
  let res = await connectConsole({ container_id: data });
  console.log("连接控制台", res.data.data.data);
  let token = res.data.data.data.token;
  let serevr_addr = console_url.value;
  router.push(`/self/console?token=${token}&serevr_addr=${serevr_addr}`);
};
//获取服务器名称
const serverName = ref("");
const serverIP = ref("");
const getServerName = async () => {
  let res = await selectServer({
    server_id: container_message.value.server_id
  });
  console.log("服务器信息", res.data.data.console_url);
  console_url.value = res.data.data.console_url;
  serverName.value = res.data.data.name;
  serverIP.value = res.data.data.server_ip;
};
//获取套餐名
const planName = ref("");
const getPlanName = async () => {
  let res = await selectServerPlan({
    plan_id: container_message.value.plan_id,
    server_type: "dockerContainer"
  });
  console.log("套餐信息", res.data.data);
  planName.value = res.data.data;
};

const dialogOverflowVisible = ref(false);
const form = reactive({
  type: "",
  container_id: "",
  server_port: "",
  container_port: "",
  domain: "",
  floating_ip: ""
});
const logPagin = reactive({
  count: 20,
  page: 1
});
const logTotal = ref(10);
const handleCurrentPageChange = async newPage => {
  logPagin.page = newPage;
  getLogs({ container_id: route.query.container_id, ...logPagin });
};
const handlePageSizeChange = async newSize => {
  logPagin.count = newSize;
  getLogs({ container_id: route.query.container_id, ...logPagin });
};
const container_message = ref({});
const containers_log = ref([]);

const container_connect = ref([]);

const netTypes = ref([
  { label: "port_forward", value: "port_forward" },
  { label: "nginx", value: "nginx" },
  { label: "floating_ip", value: "floating_ip" }
]);
const handleChange = () => { };
const volumes = ref([]);
function submit() {
  addNetwork({
    container_id: route.query.container_id,
    proxy_data: JSON.stringify([
      {
        type: form.type,
        container_id: route.query.container_id,
        container_port: form.container_port,
        domain: form.domain
      }
    ])
  }).then(res => {
    console.log(res);
    if (res.data.code == 400) {
      message(res.data.msg, { type: "error" });
    } else {
      message("添加成功", { type: "success" });
      dialogOverflowVisible.value = false;
      for (const key in form) {
        if (form.hasOwnProperty(key)) {
          form[key] = "";
        }
      }
      getNetworkList(route.query.container_id).then(res1 => {
        container_connect.value = res1.data;
      });
    }
  });
}
const childRef = ref();
const file = a => {
  console.log(a, 111111);
  childRef.value.outer();
};
// 删除网络
const delconnect = async (id, cid) => {
  let { data } = await delContainer({
    container_id: cid,
    connect_id: id
  });
  await gettwolist();
};
// 获取屏幕大小
const contWith = ref(4);
const setWideth = () => {
  if (window.innerWidth < 800) {
    contWith.value = 1;
  } else {
    contWith.value = 4;
  }
};
// 判断价格
const contaimoney = ref(0);
const setpay = async container_id => {
  const regex = /^\d+(\.\d{1,2})?$/;
  if (!regex.test(contaimoney.value)) {
    message("请输入正确的价格", { type: "error" });
    contaimoney.value = container_message.value.pay;
  } else {
    let { data } = await Containerpay({
      container_id,
      pay: contaimoney.value
    });
    if (data.code == 200) {
      await getcontaiinfo(contaimoney.value);
      message("修改成功", { type: "success" });
    }
  }
};
// 容器日期
const conttimes = ref();
const containerPacker = async (val: string | null) => {
  const selectedDate = new Date(val);
  const timestamp = Math.floor(selectedDate.getTime() / 1000);
  console.log(timestamp, container_message.value.container_id);
  let { data } = await Containertime({
    container_id: container_message.value.container_id,
    expire_time: timestamp
  });
  if (data.code == 200) {
    message("修改成功", { type: "success" });
    await getcontaiinfo("", timestamp);
  }
};
//重装
const image_dialog = ref(false);
const image_list = ref([]);
const image_id = ref();
const image = ref({});
const images = ref();
const getImage = async () => {
  getMirrorList(container_message.value.server_id).then(res => {
    res = res.data.data;
    image.value = res.filter(
      item => item.image_id == container_message.value.image_id
    )[0];
    console.log("镜像信息", typeof image.value);
  });
};
const toRein = async () => {
  image_dialog.value = true;
  let res = await getMirrorList(container_message.value.server_id);
  res = res.data.data;
  image_list.value = res.map(item => {
    return {
      label: item.show_name,
      value: item.image_id
    };
  });
};
const torein = () => {
  const loading = ElLoading.service({
    lock: true,
    text: "容器重装中..."
  });
  reinstallC({
    container_id: container_message.value.container_id,
    image_id: image_id.value
  })
    .then(res => {
      if (res.data.code == 200 && res.data.data.data.container_uuid) {
        message("容器重装完成", { type: "success" });
        loading.close();
        router.push(
          `/servers/containers?container_id=${res.data.data.data.container_uuid}`
        );
      }
    })
    .catch(e => {
      message("重装失败", { type: "error" });
      loading.close();
    });
};
//镜像变量
const objectToString = obj => {
  console.log("镜像信息", obj);
  obj = JSON.parse(obj);
  if (
    obj &&
    typeof obj === "object" &&
    !Array.isArray(obj) &&
    Object.keys(obj).length > 0
  ) {
    return Object.entries(obj);
  } else {
    return "";
  }
};
const setupstop = ref(false);
const textstop = ref();
const stopId = ref();
// 暂停容器&&恢复容器
const butstoped = async (isstop, id) => {
  if (!isstop) {
    setupstop.value = true;
    stopId.value = id;
  } else {
    const loading = ElLoading.service({
      lock: true,
      text: "解除暂停中.....",
      background: "rgba(0, 0, 0, 0.7)"
    });
    let { data } = await unpauseContainer({
      container_id: id
    });
    if (data.code == 200) {
      message(data.data, { type: "success" });
      loading.close();
      await getcontaiinfo();
    } else {
      message(data.data, { type: "error" });
      loading.close();
    }
  }
};
// 确认暂停
const okstop = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: "暂停中.....",
    background: "rgba(0, 0, 0, 0.7)"
  });
  let { data } = await pauseContainer({
    container_id: stopId.value,
    stop_info: textstop.value
  });
  if (data.code == 200) {
    setupstop.value = false;
    loading.close();
    message(data.data, { type: "success" });
    await getcontaiinfo();
  } else {
    message(data.data, { type: "error" });
    loading.close();
  }
};

// 添加https
const httpscert = ref(false);
const infohttps = ref();
const Addhttps = (data: any) => {
  httpscert.value = true;
  infohttps.value = data;
  infohttps.value["user_id"] = container_message.value.user_id || "";
  console.log(data, infohttps.value);
};
const offdialog = () => {
  httpscert.value = false;
};
// 删除https
const delhttps = async (data: any) => {
  await AdminDelHttps({
    connect_id: data.connect_id,
    container_id: data.container_id
  }).then((res: any) => {
    if (res.data.code == 200) {
      message("删除成功！", { type: "success" });
      gettwolist();
    }
  });
};
</script>
<template>
  <div class="body">
    <el-descriptions title="容器信息" direction="vertical" :column="contWith" size="default" border>
      <el-descriptions-item label="容器 ID">{{
        container_message.container_id
        }}</el-descriptions-item>
      <el-descriptions-item label="价格">
        <el-input v-model="contaimoney" type="number" style="width: 100px" placeholder="Please input"
          @change="setpay(container_message.container_id)" /><span style="margin-left: 10px">元</span>
      </el-descriptions-item>
      <el-descriptions-item label="所属服务器">{{
        serverName
        }}</el-descriptions-item>
      <el-descriptions-item label="服务器IP">{{
        serverIP
        }}</el-descriptions-item>
      <el-descriptions-item label="创建时间">
        <el-tag size="small">{{ container_message.created_at }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="到期时间">
        <el-date-picker v-model="conttimes" type="datetime" placeholder="到期时间" format="YYYY-MM-DD HH:mm:ss"
          date-format="MMM DD, YYYY" time-format="HH:mm" @change="containerPacker" />
      </el-descriptions-item>
      <el-descriptions-item label="所属套餐">{{
        planName.name
        }}</el-descriptions-item>
      <el-descriptions-item label="内存">{{ planName.memory }}MB</el-descriptions-item>
      <el-descriptions-item label="硬盘">{{ planName.disk }}GB</el-descriptions-item>
      <el-descriptions-item label="cpu">{{ planName.cpu }}毫核</el-descriptions-item>
      <el-descriptions-item label="带宽">{{ Math.floor(planName.bandwidth_tx) }}mbps/{{
        Math.floor(planName.bandwidth_rx)
      }}mbps</el-descriptions-item>
      <el-descriptions-item label="镜像">{{
        image.show_name ? image.show_name : image.name
        }}</el-descriptions-item>
      <el-descriptions-item label="容器IP">{{
        container_message.container_ip
        }}</el-descriptions-item>
      <el-descriptions-item label="状态">
        <el-tag :type="container_state == 0 || container_state == 1
            ? 'info'
            : container_state == 2
              ? 'success'
              : 'danger'
          ">{{
            container_state == 0
              ? "未支付"
              : container_state == 1
                ? "未开通"
                : container_state == 2
                  ? "开机"
                  : "关机"
          }}</el-tag></el-descriptions-item>
      <el-descriptions-item :span="4" label="操作">
        <el-col :span="24" :xs="24">
          <el-button type="primary" plain :icon="CircleCheckFilled"
            @click="openIt(container_message.container_id)">开通</el-button>
          <!-- <el-button type="primary" plain :icon="CreditCard">续费</el-button> -->
          <el-button type="success" plain :icon="CircleCheck"
            @click="startIt(container_message.container_id)">开机</el-button>
          <el-button type="info" plain :icon="SwitchButton"
            @click="stopIt(container_message.container_id)">关机</el-button>
          <el-button type="danger" plain :icon="Clock" @click="
            butstoped(
              container_message.stoped,
              container_message.container_id
            )
            ">{{ container_message.stoped ? "解除暂停" : "暂停" }}</el-button>
          <el-button type="warning" plain :icon="Refresh"
            @click="restartIt(container_message.container_id)">重启</el-button>
          <el-button type="warning" :icon="Refresh" plain @click="toRein">重装</el-button>
          <el-button type="danger" plain :icon="Delete" @click="deleteIt(container_message.container_id)">删除</el-button>
          <el-button type="danger" plain :icon="Delete"
            @click="clearIt(container_message.container_id)">清除流量</el-button>
          <el-button :disabled="container_state != 2" @click="file(container_state)">文件管理</el-button>
          <el-button type="primary" :disabled="container_state != 2"
            @click="connectIt(container_message.container_id)">连接控制台</el-button>
        </el-col>
      </el-descriptions-item>
      <el-descriptions-item :span="8" label="镜像变量"><el-tag v-for="item in images" v-if="images != ''"
          style="margin-right: 10px">{{ item[0] }}:{{ item[1] }}</el-tag></el-descriptions-item>
      <el-descriptions-item :span="8" label="镜像描述">
        <div class="mytitle">{{ image.description }}</div>
      </el-descriptions-item>
    </el-descriptions>
    <FileManage ref="childRef" />
    <!-- tab栏 -->
    <el-tabs type="border-card" class="info_table">
      <el-tab-pane label="容器日志">
        <el-table :data="containers_log" style="width: 100%">
          <el-table-column prop="created_at" label="时间" />
          <el-table-column prop="action_info" label="日志" />
        </el-table>

        <el-pagination background layout="prev, pager, next,sizes" :total="logTotal" :current-page="logPagin.page"
          :page-size="logPagin.count" :page-sizes="[1, 10, 20]" @update:current-page="handleCurrentPageChange"
          @update:page-size="handlePageSizeChange" />
      </el-tab-pane>
      <el-tab-pane label="网络信息">
        <el-button type="primary" @click="dialogOverflowVisible = true">添加网络</el-button>
        <el-table class="table_el" :data="container_connect" style="width: auto">
          <el-table-column label="ID" prop="connect_id" />
          <el-table-column label="网络类型" prop="connect_type" />
          <el-table-column label="外部访问端口" prop="server_port" />
          <el-table-column label="内部端口" prop="container_port" />
          <el-table-column label="容器IP" prop="container_ip" />
          <el-table-column label="浮动IP" prop="floating_ip" />
          <el-table-column label="域名" prop="domain" />
          <el-table-column label="创建时间" prop="created_at" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-row :gutter="24">
                <el-col :span="24">
                  <el-button type="danger" plain @click="
                    delconnect(scope.row.connect_id, scope.row.container_id)
                    ">删除</el-button>
                </el-col>
                <el-col v-if="!scope.row.ssl_cert && route.query.type == 'nginx'" :span="24">
                  <el-button type="primary" plain @click="Addhttps(scope.row)">添加https</el-button>
                </el-col>
                <el-col v-if="scope.row.ssl_cert && route.query.type == 'nginx'" :span="24">
                  <el-button type="danger" plain @click="delhttps(scope.row)">删除https</el-button>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="数据卷信息">
        <el-table class="table_el" :data="volumes" style="width: auto">
          <el-table-column label="ID" prop="volume_id" />
          <el-table-column label="空间大小(MB)" prop="size" />
          <el-table-column label="挂载路径" prop="mount_path" />
          <el-table-column label="创建时间" prop="created_at" />
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <el-dialog v-model="dialogOverflowVisible" title="网络信息111" width="500" draggable overflow>
      <div>
        <el-form :model="form" label-width="auto" style="max-width: 600px">
          <el-form-item label="网络类型">
            <el-select v-model="form.type" placeholder="请选择" style="width: 240px" @change="handleChange()">
              <el-option v-for="item in netTypes" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.type == 'port_forward' || form.type == 'nginx'" label="容器内部端口号" :rules="[
            {
              required: true,
              message: '请输入容器内部端口号',
              trigger: 'blur'
            }
          ]">
            <el-input v-model="form.container_port" type="number" :min="1" :max="65535" placeholder="端口号应在1-65535之间" />
          </el-form-item>
          <el-form-item v-if="form.type == 'nginx'" label="域名">
            <el-input v-model="form.domain" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogOverflowVisible = false">关闭</el-button>
          <el-button type="primary" @click="submit()"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="image_dialog" title="重装" width="40%">
      <el-form>
        <el-form-item label="镜像">
          <el-select v-model="image_id" placeholder="你可以选择重装镜像">
            <el-option v-for="item in image_list" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="image_dialog = false">关闭</el-button>
          <el-button type="primary" @click="torein">确认重装</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="setupstop" title="暂停原因" width="800">
      <el-input v-model="textstop" style="width: 100%" autosize type="textarea" placeholder="请输入暂停原因" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="setupstop = false">取消</el-button>
          <el-button type="primary" @click="okstop()"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="httpscert" title="请填写信息" width="800" align-center>
      <AddHttps :info="infohttps" @off="offdialog" />
    </el-dialog>
  </div>
</template>
<style scoped>
.el-descriptions {
  margin-top: 20px;
}

.info_table {
  margin: 20px 0;
}

:deep(.el-col) {
  margin-top: 5px;
}

.mytitle {
  max-width: 800px;
  overflow: hidden;
  word-break: break-all;
  word-wrap: break-word;
}
</style>
